<template>
	<view>
		<view>
			<text>用户头像</text>
			<u-upload
				:fileList="fileList"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				maxCount="1"
				maxSize='70000'
				@oversize='oversize'
			></u-upload>
		</view>
	
	</view>
</template>

<script>
import { updateUser } from '@/api/me.js'
import { getUserInfo } from '@/api/login.js'
import { mapState , mapMutations } from 'vuex'
export default{
	data () {
		return {
			fileList:[],//展示的数据
		}
	},
	computed:{
		...mapState({
			userInfo:state=>state.user.userInfo
		})
	},
	onLoad(){
		this.fileList.push({
			url:this.userInfo.avatar
		})
	},
	methods:{
		...mapMutations(['setUserInfo']),
		//图片上传后
		afterRead( event ){

			let imgUrl = event.file.url;
			//在视图展示
			this.fileList.push({
				url:imgUrl
			})
			//请求接口
			updateUser({
				avatar:imgUrl
			}).then(res=>{
				if( res.code != 0 ) alert('上传不成功');
				//更新用户信息==>本地
				getUserInfo().then(res=>{
					//用户信息存储在vuex中了
					this.setUserInfo( res.data );
				})
			})
		},
		//删除图片
		deletePic( event ){
			this.fileList.splice(event.index, 1);
		},
		//上传图片过大
		oversize( event ){
			alert('上传的图片多大')
		}
	}
}
</script>

<style>
</style>